﻿using System;
using System.Web.Mvc;
using TaskManager.Web.Controls;

namespace TaskManager.Web.Filters
{
    /// <summary>
    /// Sets active tab based on route values collection
    /// </summary>
    public class UpdateActiveTabAttribute : ActionFilterAttribute
    {
        public TabContainer TabContainer { get; set; }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            // Ignore child requests and AJAX requests

            if (filterContext.IsChildAction)
                return;
            if(filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
                return;

            int tab = 0;

            if(filterContext.RouteData.Values.ContainsKey("tab"))
            {
                tab = int.Parse(filterContext.RouteData.Values["tab"].ToString());
            }

            TabContainer.ActiveTab = tab;
        }

        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            var result = filterContext.Result as ViewResultBase;

            if (result != null)
            {
                result.ViewBag.Tab = TabContainer.ActiveTab;
            }
        }
    }
}